package cn.yajienet.data.elasticsearch.init;

import cn.yajienet.data.elasticsearch.annotation.Document;
import cn.yajienet.data.elasticsearch.context.ElasticSearchContext;
import cn.yajienet.data.elasticsearch.document.InitializeDocument;
import cn.yajienet.data.elasticsearch.dto.DocumentEntity;
import cn.yajienet.data.elasticsearch.utils.GeneralTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author Wang Chenguang
 * @Email wcg.chen@foxmail.com
 * @Date on 2021/12/19
 * @Version 1.0.0
 * @Description 全部文档自动初始化，方式是：先删除后初始化
 */
@Slf4j
@Component
public class AutomaticInitialization extends AbstractRunInitialization {


    @Override
    public void init(ApplicationArguments args) {
        log.info( "---------- start initialize elasticsearch ----------" );
        scanDocumentScanPackages();
        // 先检查文档索引
        ElasticSearchContext.checkDocuments();
        // 开始初始化
        scanLoadData();
        initializeDocument();
        log.info( "----------  initialize elasticsearch end  ----------" );
        initializeData(false);
        startLoadData();
    }


    /**
     * 初始化文档
     *
     * @author Wang Chenguang
     * @date 2021/10/17
     */
    private void initializeDocument() {
        List<Class<?>> classList = new ArrayList<>( ElasticSearchContext.getDocumentsClass() );
        for (Class<?> aClass : classList) {
            try {
                Document document = aClass.getAnnotation( Document.class );
                InitializeDocument initializeDocument = this.setInitializeDocument( document, aClass );
                DocumentEntity documentEntity = GeneralTools.toDocumentEntity( document, aClass.getSimpleName(), elasticSearchProperties,false);
                if (Objects.nonNull( documentEntity )) {
                    initializeDocument.setDocumentEntity( documentEntity);
                    if (initializeDocument.delete(false)) {
                        initializeDocument.initialize();
                        log.info( "已经完成文档[{} - {}]的结构的初始化！", aClass.getName(), document.index() );
                    } else {
                        log.info( "原文档[{} - {}]未删除不能初始化！", aClass.getName(), document.index() );
                        errorDocument.add( aClass );
                    }
                }else {
                    log.error( "[{}]未设置索引(Index)，跳过初始化此文档！", aClass.getName() );
                }
            } catch (Exception e) {
                log.error( "未获取到文档[{}]对象，无法初始化此文档！", aClass.getName(), e );
                errorDocument.add( aClass );
            }
        }
    }




}
